/**
 * 选择的文件转URL
 */
export function fileToUrl(file) {
  return window.URL.createObjectURL(file)
}
/**
 * 选择文件转base64
 */
export function fileToBase64(file,) {
  return new Promise(resolve => {
    const reader = new FileReader()

    reader.onloadend = function() {
      resolve(reader.result)
    }
    reader.readAsDataURL(file)
  })
}

/**
 * 计算文件大小
 */
export function renderSize(fsize) {
  const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

  const srcsize = parseFloat(fsize)

  const index = Math.floor(Math.log(srcsize) / Math.log(1024))

  const size = (srcsize / Math.pow(1024, index)).toFixed(2)

  return size + unitArr[ index ]
}

/**
 * 下载buffer文件
 * @param {String} url 资源地址
 * @param {String} filename 文件名
 */
export async function loadBufferFile(url, filename) {
  try {
    const loadRes = await axios.get(url, {
      responseType: 'arraybuffer'
    })

    const href = window.URL.createObjectURL(new Blob([loadRes.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
    const link = document.createElement('a')

    link.style.display = 'none'
    link.href = href
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (err) {
    return Promise.reject(err)
  }
}

